﻿#include "mcommon.h"

#include <QApplication>
#include <QDebug>
#include <QFile>
#include <QPalette>
#include <QTime>
#include <QTranslator>
#include <QWidget>
#include <QDesktopWidget>
#include <QMutex>
#include <QTextStream>
#include <QReadWriteLock>
#include <QSemaphore>
#include <QMutex>
#include <QProcess>

void MCommon::AutoRunWithSystem(bool IsAutoRun, const QString & AppName, const QString & AppPath)
{
#if defined (Q_OS_WIN)
    QSettings *reg = new QSettings(
        "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
        QSettings::NativeFormat);

    if (IsAutoRun) {
        reg->setValue(AppName, AppPath);
    } else {
        reg->setValue(AppName, "");
    }
#else
    Q_UNUSED(IsAutoRun)
    Q_UNUSED(AppName)
    Q_UNUSED(AppPath)
#endif
}

//设置编码为UTF8
void MCommon::SetUTF8Code()
{
#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0))
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForLocale(codec);
    QTextCodec::setCodecForCStrings(codec);
    QTextCodec::setCodecForTr(codec);
#endif
}

//设置皮肤样式
void MCommon::SetStyle(const QString &styleName)
{
    /* 指定文件 */
    QFile file(QString(":/new/prefix1/%1.qss").arg(styleName));
    /* 判断文件是否存在 */
    if (file.exists() == false){
        qDebug()<<styleName<<".qss isn't exists!";
        return ;
    }

    file.open(QFile::ReadOnly);
    /* 以字符串的方式保存读出的结果 */
    QString qss = QLatin1String(file.readAll());
    /* 设置全局样式 */
    qApp->setStyleSheet(qss);
    qApp->setPalette(QPalette(QColor("#F0F0F0")));

    file.close();
}

//加载中文字符
void MCommon::SetChinese()
{
    QTranslator *translator = new QTranslator(qApp);
    translator->load(":/image/qt_zh_CN.qm");
    qApp->installTranslator(translator);
}

//判断是否是IP地址
bool MCommon::IsIP(QString IP)
{
    QRegExp RegExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
    return RegExp.exactMatch(IP);
}

//延时
void MCommon::Sleep(int sec)
{
    QTime dieTime = QTime::currentTime().addMSecs(sec);
    while ( QTime::currentTime() < dieTime ) {
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
    }
}

//窗体居中显示
void MCommon::FormInCenter(QWidget *frm)
{
    int frmX = frm->width();
    int frmY = frm->height();
    QDesktopWidget w;
    int deskWidth = w.width();
    int deskHeight = w.height();
    QPoint movePoint(deskWidth / 2 - frmX / 2, deskHeight / 2 - frmY / 2);
    frm->move(movePoint);
}

//重定位调试信息输出
void MCommon::outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

    QString text;
    switch(type)
    {
    case QtMsgType::QtDebugMsg:
       text = QString("Debug:");
       break;

    case QtMsgType::QtWarningMsg:
       text = QString("Warning:");
       break;

    case QtMsgType::QtCriticalMsg:
       text = QString("Critical:");
       break;

    case QtMsgType::QtFatalMsg:
       text = QString("Fatal:");
       break;

    default: break;
    }

    QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString current_date = QString("(%1)").arg(current_date_time);
    QString message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);

    QFile file("log.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream << message << "\r\n";
    file.flush();
    file.close();

    mutex.unlock();
}

//设置系统时间
//传入字符数据 例：2011.12.27.09.14.00
void MCommon::SetSytemTime(const QString & timeStr)
{
    QStringList timeList =  timeStr.split(".");
    if (timeList.length() != 6)
        return ;

    QString str = "date -s " + timeList.at(1) + "/" + timeList.at(2) + "/" + timeList.at(0);
    system(str.toLatin1().data());

    str = "date -s " + timeList.at(3) + ":" + timeList.at(4) + ":" + timeList.at(5);
    system(str.toLatin1().data());
    //强制写入到CMOS
    //system("clock -w");
}

//设置语言
void MCommon::InitUiByLanguage(const QString & strLanguage)
{
    if (strLanguage.isEmpty())
        return;

    QString strLanguageFile;
    if (strLanguage.compare("en") == 0)
    {
        strLanguageFile = ":/new/prefix1/rk_en_CN.qm";
    }
    else if (strLanguage.compare("zh") == 0)
    {
        strLanguageFile = ":/new/prefix1/rk_zh_CN.qm";
    }else{
        qDebug()<<"unknown language!";
        return ;
    }

    static QTranslator translator;
    if (!QFile(strLanguageFile).exists())
    {
        qDebug() << "language file does not exists ...";
        return ;
    }
    translator.load(strLanguageFile);
    qApp->installTranslator(&translator);
}

void MCommon::InitAppInfor(const QString &name, const QString & version)
{
    QString appName = name + version;
    QCoreApplication::setApplicationName(appName);
    QCoreApplication::setApplicationVersion(version);
    QCoreApplication::setOrganizationName("DJYL");
    QCoreApplication::setOrganizationDomain("www.dajingmed.com/");
}

bool MCommon::ShellProcess(const QString &cmd, const QStringList &param, QString &output)
{
    QProcess process;

    process.start(cmd, param);
    // 等待进程启动
    if (!process.waitForStarted()){
        qDebug()<<"waitForStarted error";
        return false;
    }
    process.closeWriteChannel();

    // 用于保存进程的控制台输出
    while (!process.waitForFinished(500))
    {
        qDebug()<<"waitForFinished error";
        process.close();
        return false;
    }
    output = process.readAll();

    return true;
}
